//
//  ScheduleView.m
//  HarmonizePub
//
//  Created by rzhy on 2016/11/17.
//  Copyright © 2016年 Zy. All rights reserved.
//

#import "ScheduleView.h"
#import "Config.h"
#import "ScheduleCollectionViewCell.h"

static NSString * const CellIdentifier = @"Cell";

@interface ScheduleView () <UICollectionViewDataSource, UICollectionViewDelegate>
{
    NSMutableArray *_dataArrayM;
}
@property (weak, nonatomic) IBOutlet UIView *calendarView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) AppointmentBlock appointmentBlock;

@end

@implementation ScheduleView

+ (instancetype)scheduleViewWithAppointmentBlock:(AppointmentBlock)appointmentBlock {
    ScheduleView *schedule = [[NSBundle mainBundle] loadNibNamed:@"ScheduleView" owner:nil options:nil].lastObject;
    schedule.appointmentBlock = appointmentBlock;
    return schedule;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    [self createLabel];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    CGFloat itemWidth = (XHScreenWidth - 65.0) / 7;
    flowLayout.itemSize = CGSizeMake(itemWidth, [ScheduleCollectionViewCell itemHeight]);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.collectionView.collectionViewLayout = flowLayout;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    UINib *nib = [UINib nibWithNibName:[ScheduleCollectionViewCell registerName] bundle:nil];
    [self.collectionView registerNib:nib forCellWithReuseIdentifier:CellIdentifier];
}

- (void)setDataDict:(NSDictionary *)dataDict {
    _dataDict = dataDict;
    for (UILabel *label in self.calendarView.subviews)
        if ([label isKindOfClass:[UILabel class]])
            label.text = dataDict[@"title"][label.tag];
    [self.collectionView reloadData];
}

- (void)createLabel {
    CGFloat labelW = (XHScreenWidth - 65.0) / 7;
    CGFloat labelH = 50.0f;
    for (NSInteger i= 0; i < 7; i++) {
        UILabel *label = [[UILabel alloc] init];
        label.tag = i;
        label.numberOfLines = 0;
        label.textColor = [UIColor lightGrayColor];
        label.font = [UIFont systemFontOfSize:14.0f];
        label.textAlignment = NSTextAlignmentCenter;
        CGRect rect = CGRectMake(i * labelW, 0, labelW, labelH);
        label.frame = rect;
        [self.calendarView addSubview:label];
        
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor lightGrayColor];
        view.frame = CGRectMake(rect.origin.x + rect.size.width - 0.5f, rect.origin.y, 0.5f, rect.size.height);
        [self.calendarView addSubview:view];
    }
}

#pragma mark - collectionView delegate/dataSource Method
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.dataDict[@"title"] count] * 2;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ScheduleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.isBoolean = [self dataCalculationWithIndex:indexPath.item];
    return cell;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    return [self dataCalculationWithIndex:indexPath.item];
}
/**
 * no comments for you.
 * it was hard to write.
 * so it should be hard to read.
 *
 * 难写的代码，肯定很难读。因此，我没有注释留给你.
 */
- (BOOL)dataCalculationWithIndex:(NSInteger)index {
    NSArray *titleArray = self.dataDict[@"title"];
    _dataArrayM = [NSMutableArray arrayWithCapacity:[self.dataDict[@"content"] count]];
    for (NSDictionary *dict in self.dataDict[@"content"]) {
        NSMutableDictionary *dictM = [dict mutableCopy];
//        NSDate *date = [dictM[@"jzrq"] dateStringWithFormat:@"yyyyMMdd"];
        NSDate *date = [dictM[@"jzrq"] dateStringWithFormat:@"yyyy-MM-dd"];
        NSString *calendar = [NSString stringAnalysisWithDate:date format:@"MM-dd"];
        NSString *weekday = [NSString stringWeekdayWithFromDate:date weekType:WeekdayDateStringTypeZhou];
        NSString *string = [NSString stringWithFormat:@"%@\n%@", calendar, weekday];
        [dictM setObject:string forKey:@"title"];
        [_dataArrayM addObject:dictM];
    }
    if (index / 7 == 0) {
        // 上午
        NSString *title = titleArray[index % 7];
        for (NSInteger i = 0; i < _dataArrayM.count; i++) {
            NSDictionary *dict = _dataArrayM[i];
            if ([title isEqualToString:dict[@"title"]] && [dict[@"sdbz"] integerValue] == 1) {
                return YES;
            } else {
                if (i == _dataArrayM.count - 1) 
                    return NO;
            }
        }
    } else {
        // 下午
        NSString *title = titleArray[index % 7];
        for (NSInteger i = 0; i < _dataArrayM.count; i++) {
            NSDictionary *dict = _dataArrayM[i];
            if ([title isEqualToString:dict[@"title"]] && [dict[@"sdbz"] integerValue] == 2) {
                return YES;
            } else {
                if (i == _dataArrayM.count - 1) 
                    return NO;
            }
        }
    }
    return NO;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *title = self.dataDict[@"title"][indexPath.item % 7];
    NSInteger sdbz = indexPath.item / 7 + 1;
    NSDictionary *dataDict = [NSDictionary dictionary];
    for (NSDictionary *dict in _dataArrayM)
        if ([title isEqualToString:dict[@"title"]] && [dict[@"sdbz"] integerValue] == sdbz)
            dataDict = dict;
    self.appointmentBlock(dataDict);
}

- (void)setFrame:(CGRect)frame {
    frame.size.width = XHScreenWidth;
    [super setFrame:frame];
}

@end
